<?php

namespace app\admin\controller;


use app\admin\common\Common;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\Request;

class Email extends LoginThere
{
    public function index(){
        try {
            $listemail = Db::name('email')->where('id', 1)->find();
            return $this->fetch('email/index')->assign('email',$listemail);
        } catch (DataNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (ModelNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (DbException $e) {
             return Common::result(400,$e->getMessage());
        }

    }

    public function TestEmail(Request $request){
        $data = $request->param();
        try {
            $result = Db::name('email')->where('id', 1)->find();
        } catch (DataNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (ModelNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (DbException $e) {
             return Common::result(400,$e->getMessage());
        }
        if ($result['username'] == ""){
            return Common::result(400,"你还没有配置邮箱呢");
        }
        if ($data['test_email'] == ""){
            return Common::result(400,"你还没有输入测试邮箱呢");
        }
        return Common::send_mail($data['test_email'],$result['email_title'], $result['email_content']);
    }

    public function updateEmail(Request $request){
        $data = $request->param();
        $update = [
            'username' => $data['username'],
            'port' => $data['port'],
            'mail_way' => $data['mail_way'],
            'password' => $data['password'],
            'email_title' => $data['email_title'],
        ];
        try {
            $app = Db::name('email')->where('id', 1)->update($update);
        } catch (PDOException $e) {
             return Common::result(400,$e->getMessage());
        } catch (\think\Exception $e) {
             return Common::result(400,$e->getMessage());
        }
        if ($app>0){
            return Common::result(200,'修改成功');
        }else{
            return Common::result(400,'你未做任何修改！');
        }
    }
}